const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

// 创建集合云函数入口函数
exports.main = async (event, context) => {
  try {
    // 请求参数
    let {
      pageNum = 1, pageSize = 10, conditions,
    } = event.data

    if (typeof conditions == "string") {
      // 未传递筛选条件时 conditions会默认等于"1"
      conditions = {}
    }

    // 构建查询条件
    let query = db.collection('agentDiscountRecord')

    // 时间范围筛选
    if (conditions.startTime && conditions.endTime) {
      conditions = {
        ...conditions,
        registerTime: db.command.gte(new Date(conditions.startTime)) // 大于等于开始时间
          .and(db.command.lte(new Date(conditions.endTime))) // 小于等于结束时间
      }
      delete conditions.startTime
      delete conditions.endTime
    }

    query = query.where(conditions) // 添加筛选条件
    query = query.orderBy('createTime', 'desc') // 排序

    const skip = (pageNum - 1) * pageSize // 计算跳过的记录数

    // 查询数据
    const data = await query
      .skip(skip)
      .limit(pageSize)
      .get()

    data.data.forEach(item => {
      // 日期格式化
      const date = new Date(item.createTime)
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      // 时、分、秒
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      item.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    })

    // 获取总数
    const countResult = await query.count()

    // 返回查询结果
    return {
      code: 200,
      msg: "操作成功",
      data: data.data,
      total: countResult.total,
      totalPages: Math.ceil(countResult.total / pageSize),
    }
  } catch (err) {
    return {
      code: 500,
      message: err.message
    }
  }
};